<template>
  <div id="specSampling">
    <el-tabs v-model="activeName" type="border-card">
      <el-tab-pane label="标本送达" name="specSampling">
        <div>
          <vxe-toolbar perfect>
            <template #buttons>
              <span class="margin-lr-xs text-Bold text-shadow">条码号:</span>
              <vxe-input ref="specCodeInput" v-model="form.specCode" clearable @compositionstart.native="compositionstart" @compositionend.native="compositionend" @keyup="specInputKeyUp"></vxe-input>
            </template>
            <template #tools>
              <span class="text-bold text-df margin-lr-xs vxe-icon-square-fill solid-bottom">标本采集</span>
            </template>
          </vxe-toolbar>
        </div>
        <div class="padding-xs" style="background-color: #f8f8f9">
          <div style="border: 1px dashed green; width: 100%" class="radius line-olive flex justify-start bg-gray">
            <div style="width: 70px; padding: 2.5px" class="flex justify-center text-center">
              <div style="width: 65px; height: 100%" class="radius solid bg-green"></div>
            </div>
            <div style="height: 100%" class="bg-gray">
              <vxe-form :data="currentSpecsamplingDetail" class-name="padding-xs width-100-percentage" style="background-color: rgba(0, 0, 0, 0)" title-width="70px">
                <vxe-form-gather span="6">
                  <vxe-form-item title="条码号" field="reqNo" class-name="width-100-percentage">
                    <!-- <template #title>
                      <span class="text-bold padding-left-xs">条码号</span>
                    </template> -->
                    <template #default="{ data }">
                      <vxe-input v-model="data.reqNo" readonly placeholder="条码号" class-name="width-100-percentage" />
                    </template>
                  </vxe-form-item>
                </vxe-form-gather>
                <vxe-form-gather span="6">
                  <vxe-form-item title="申请号" field="hisReqId" class-name="width-100-percentage">
                    <template #title>
                      <span class="text-bold padding-left-xs">申请号</span>
                    </template>
                    <template #default="{ data }">
                      <vxe-input v-model="data.hisReqId" readonly placeholder="申请号" class-name="width-100-percentage" />
                    </template>
                  </vxe-form-item>
                </vxe-form-gather>
                <vxe-form-gather span="6">
                  <vxe-form-item title="病人ID号" field="patId" class-name="width-100-percentage">
                    <template #title>
                      <span class="text-bold padding-left-xs">病人ID号</span>
                    </template>
                    <template #default="{ data }">
                      <vxe-input v-model="data.patId" readonly placeholder="病人ID号" class-name="width-100-percentage" />
                    </template>
                  </vxe-form-item>
                </vxe-form-gather>
                <vxe-form-gather span="6">
                  <vxe-form-item title="姓名" field="patNa" class-name="width-100-percentage">
                    <template #title>
                      <span class="text-bold padding-left-xs">姓名</span>
                    </template>
                    <template #default="{ data }">
                      <vxe-input v-model="data.patNa" readonly placeholder="姓名" class-name="width-100-percentage" />
                    </template>
                  </vxe-form-item>
                </vxe-form-gather>
                <vxe-form-gather span="6">
                  <vxe-form-item title="性别" field="sex" class-name="width-100-percentage">
                    <template #title>
                      <span class="text-bold padding-left-xs">性别</span>
                    </template>
                    <template #default="{ data }">
                      <vxe-input v-model="data.sex" readonly placeholder="性别" class-name="width-100-percentage" />
                    </template>
                  </vxe-form-item>
                </vxe-form-gather>
                <!-- <vxe-form-gather span="6">
                  <vxe-form-item title="容器" field="specContainer" class-name="width-100-percentage">
                    <template #title>
                      <span class="text-bold padding-left-xs">容器</span>
                    </template>
                    <template #default="{ data }">
                      <vxe-input :value="data.specContainer ? data.specContainer.name : ''" readonly placeholder="采样部位"
                        class-name="width-100-percentage" />
                    </template>
                  </vxe-form-item>
                </vxe-form-gather>
                <vxe-form-gather span="6">
                  <vxe-form-item title="采样部位" field="samplingSite" class-name="width-100-percentage">
                    <template #title>
                      <span class="text-bold padding-left-xs">采样部位</span>
                    </template>
                    <template #default="{ data }">
                      <vxe-input :value="data.samplingSite ? data.samplingSite.name : ''" readonly placeholder="采样部位"
                        class-name="width-100-percentage" />
                    </template>
                  </vxe-form-item>
                </vxe-form-gather>
                <vxe-form-gather span="6">
                  <vxe-form-item title="采样方法" field="samplingMethod" class-name="width-100-percentage">
                    <template #title>
                      <span class="text-bold padding-left-xs">采样方法</span>
                    </template>
                    <template #default="{ data }">
                      <vxe-input :value="data.samplingMethod ? data.samplingMethod.name : ''" readonly placeholder="采样方法"
                        class-name="width-100-percentage" />
                    </template>
                  </vxe-form-item>
                </vxe-form-gather>
                <vxe-form-gather span="6">
                  <vxe-form-item title="样本量" field="specAmount" class-name="width-100-percentage">
                    <template #title>
                      <span class="text-bold padding-left-xs">样本量</span>
                    </template>
                    <template #default="{ data }">
                      <vxe-input v-model="data.specAmount" readonly placeholder="样本量" type="number"
                        class-name="width-100-percentage" />
                    </template>
                  </vxe-form-item>
                </vxe-form-gather> -->
                <vxe-form-gather span="6">
                  <vxe-form-item title="签收状态" field="isSign" class-name="width-100-percentage">
                    <template #title>
                      <span class="text-bold padding-left-xs">签收状态</span>
                    </template>
                    <template #default="{ data }">
                      <vxe-input v-model="signStatus" placeholder="签收状态" class-name="width-100-percentage" />
                    </template>
                  </vxe-form-item>
                </vxe-form-gather>
                <vxe-form-gather span="12">
                  <vxe-form-item title="项目" field="feeName" class-name="width-100-percentage">
                    <template #title>
                      <span class="text-bold padding-left-xs">项目</span>
                    </template>
                    <template #default="{ data }">
                      <vxe-input v-model="data.feeName" readonly placeholder="项目" class-name="width-100-percentage" />
                    </template>
                  </vxe-form-item>
                </vxe-form-gather>
              </vxe-form>
            </div>
          </div>
        </div>
        <div class="specSamplingDetailTable" :style="{ height: isChildren ? 'calc(100% - 40px - 40px)' : 'calc(100% - 40px - 100px - 10px)' }">
          <vxe-table ref="specSamplingDetailTable" v-loading="loading" border height="auto" :data="specSamplingDetailList" :row-config="{ isCurrent: true, isHover: true }" :keyboard-config="{ isArrow: true, isTab: true, isEdit: true }" @current-change="specSamplingDetailRowClick" resizable show-overflow>
            <!-- <vxe-column type='checkbox' width='26'></vxe-column> -->
            <vxe-column type="seq" title="序号" width="30"></vxe-column>
            <vxe-column field="isSuccess" title="状态" width="60" align="center">
              <template #default="{ row, rowIndex }">
                <span v-if="row.loading" class="text-blue">采集中...</span>
                <span v-else-if="row.isSuccess">
                  <el-icon color="#409EFC" class="no-inherit">
                    <CircleCheck />
                  </el-icon>
                </span>
                <span v-else class="text-blue" @click="againSampling(row, rowIndex)">重新采集</span>
              </template>
            </vxe-column>
            <vxe-column field="reqNo" title="条码号" width="100px">
              <template #default="{ row }">
                <span>{{ row.reqNo ? row.reqNo : '' }}</span>
              </template>
            </vxe-column>
            <vxe-column field="hisReqId" title="申请号" width="80px">
              <template #default="{ row }">
                <span>{{ row.hisReqId ? row.hisReqId : '' }}</span>
              </template>
            </vxe-column>
            <vxe-column field="isSign" title="签收状态" width="80px" align="center">
              <template #default="{ row }">
                <span :class="row.isSign ? 'text-blue' : 'text-red'">
                  {{ row.isSign === 1 ? '已签收' : '未签收' }}
                </span>
              </template>
            </vxe-column>
            <!-- <vxe-column field="isOriginal" title="是否原始标本" width="100px" align="center">
              <template #default="{ row }">
                <span :class="row.spec.isOriginal ? 'text-blue' : 'text-red'">
                  {{ row.spec.isOriginal ? '是' : '否' }}
                </span>
              </template>
            </vxe-column> -->
            <!-- <vxe-column field="name" title="传送方式" width="100px"></vxe-column> -->
            <vxe-column field="patId" title="病人ID" width="100">
              <template #default="{ row }">
                <span>{{ row.patId ? row.patId : '' }}</span>
                <span></span>
              </template>
            </vxe-column>
            <vxe-column field="patNa" title="姓名" width="100">
              <template #default="{ row }">
                <span>{{ row.patNa ? row.patNa : '' }}</span>
                <span></span>
              </template>
            </vxe-column>
            <vxe-column field="sex" title="性别" width="100">
              <template #default="{ row }">
                <span> {{ row.sex === '1' ? '男' : row.sex === '2' ? '女' : '未知' }}</span>
                <span></span>
              </template>
            </vxe-column>
            <vxe-column field="age" title="年龄" width="100">
              <template #default="{ row }">
                <span>{{ row.age ? row.age : '' }}</span>
                <span></span>
              </template>
            </vxe-column>
            <vxe-column field="sampleTypeNa" title="样本类型" width="100">
              <template #default="{ row }">
                <span>{{ row.sampleTypeNa ? row.sampleTypeNa : '' }}</span>

              </template>
            </vxe-column>
            <vxe-column field="feeName" title="项目" width="180">
              <template #default="{ row }">
                <span>{{ row.feeName ? row.feeName : '' }}</span>
                <span></span>
              </template>
            </vxe-column>
            <vxe-column field="reqDoctorNa" title="申请人" width="80">
              <template #default="{ row }">
                <span>{{ row.reqDoctorNa ? row.reqDoctorNa : '' }}</span>
              </template>
            </vxe-column>
            <vxe-column field="reqTime" title="申请时间" width="120">
              <template #default="{ row }">
                <span>{{ row.reqTime ? row.reqTime : '' }}</span>
              </template>
            </vxe-column>
            <vxe-column field="samplingDoctorNa" title="采集人" width="80">
              <template #default="{ row }">
                <span>{{ row.samplingDoctorNa ? row.samplingDoctorNa : '' }}</span>
              </template>
            </vxe-column>
            <vxe-column field="samplingTime" title="采集时间" min-width="120">
              <template #default="{ row }">
                <span>{{ row.samplingTime ? row.samplingTime : '' }}</span>
              </template>
            </vxe-column>
          </vxe-table>
        </div>
      </el-tab-pane>
      <el-tab-pane label="标本采集历史" name="SpecSamplingHistory">
        <SpecSamplingHistory />
      </el-tab-pane>
    </el-tabs>
  </div>
</template>
<script lang="ts" setup>
import { Component, Vue, Prop, onMounted, ref, reactive, getCurrentInstance } from 'vue';
import { VXETable } from 'vxe-table';
import { AppStore } from '../../../stores/store';
import { IsEmpty, formatDateTime } from '@/utils/common';
import SpecSamplingHistory from './labSpecSamplingHistory.vue';
import { VxeMessage, VxeNotifyType } from '../../../utils/CommonMessage';
let { proxy }: any = getCurrentInstance();

let props = defineProps({}) as any;
defineExpose({});
let store = AppStore();
let userInfo = store.userInfo;
let activeName = ref('specSampling');
let lock = false; //标记是否为中文输入法
let loading = ref(false);
let specSamplingDetailList = reactive([]); //列表
let currentSpec = {} as any; //当前标本
let currentSpecsamplingDetail = reactive({
  reqNo: '',
  hisReqId: '',
  patId: '',
  patNa: '',
  sex: '',
  isSign: '',
  feeName: ''
}); //当前采集记录详情
let currentRowIndex = 0;
let form = reactive({
  specCode: '',
  realSpecCode: '',
  searchValue: ''
});
let signStatus = ref('')//form签收状态

onMounted(() => {
  (proxy.$refs.specCodeInput as any).focus();
});

// 清空 currentSpecsamplingDetail 对象的所有属性
function clearCurrentSpecsamplingDetail() {
  Object.keys(currentSpecsamplingDetail).forEach(key => {
    currentSpecsamplingDetail[key] = '';
  });
  console.log('currentSpecsamplingDetail------', currentSpecsamplingDetail);

}
// 条码号输入框清空，并获取焦点
function clearSpecCodeInput() {
  form.specCode = '';
  (proxy.$refs.specCodeInput as any).focus();
}
// 条码号输入框失去焦点
function specCodeInputBlur() {
  (proxy.$refs.specCodeInput as any).blur();
}
// 条码号输入框中文输入法开始输入
function compositionstart() {
  lock = true;
  form.realSpecCode = form.specCode;
}
// 条码号输入框中文输入法结束输入
function compositionend() {
  lock = false;
  form.specCode = form.realSpecCode;
}
// 键盘输入为中文状态，转为英文字符
function specInputKeyUp(e) {
  if (e.$event.code === 'Enter' || e.$event.code === 'NumpadEnter') {
    getspecByCode(form.specCode);
  }
  if (!lock) {
    return;
  }
  if (e.key === 'Backspace' && form.realSpecCode) {
    form.realSpecCode = form.realSpecCode.slice(0, -1);
  }
  const reg = /^[\w!@#$%^&*\(\)-+=|':./<>?`~]{1}$/;
  if (reg.test(e.key)) {
    form.realSpecCode += e.key;
  }
  // form.specCode = form.realSpecCode;
}
// 条码号回车
function specCodeInputEnter(specId, reqNo, index) {
  const url = '/lab/reqMain/createSamplingDetail';
  const data = {
    reqNo: reqNo,
    id: specId
  };
  proxy.$http
    .post(url, data)
    .then((res: any) => {
      if (res.status.code === 1) {
        res.data[0].isSuccess = true;
        res.data[0].loading = false;
        // currentSpecsamplingDetail.reqNo = res.data[0].reqNo;
        Object.assign(currentSpecsamplingDetail, res.data[0]);
        if (currentSpecsamplingDetail.isSign === 1) {
          signStatus.value = '已签收'
        } else {
          signStatus.value = '未签收'
        }
        Object.assign(specSamplingDetailList[index], res.data[0]);
      } else {
        currentSpec = {};
        clearCurrentSpecsamplingDetail();
        specSamplingDetailList.splice(index, 1);
        VxeMessage(res.status.msg, VxeNotifyType.error);
      }

    })
    .catch((err: any) => {
      specCodeInputBlur();
      currentSpec = {};
      clearCurrentSpecsamplingDetail();
      specSamplingDetailList.splice(index, 1);
      proxy.$alert(err.data.error.message, '提示', {
        callback: action => {
          const time = setTimeout(() => {
            clearSpecCodeInput();
            clearTimeout(time);
          }, 200);
        }
      });
    });
  clearSpecCodeInput();
}
// #region
// 查询标本信息
async function getspecByCode(specCode) {
  if (IsEmpty(specCode) || IsEmpty(specCode.trim())) {
    VxeMessage('条码号不可为空', VxeNotifyType.error);
    return;
  }
  const index = handleAdd(specCode);
  try {
    const url = '/lab/reqMain/getReqMainByReqNo';
    proxy.$http
      .get(url, { params: { reqNo: specCode } })
      .then(async (res: any) => {
        console.log('res', res);
        if (res.status.code === 200 && (res.data.length > 0)) {
          currentSpec = res.data;
          specSamplingDetailList[index].id = res.data[0].id;
          specSamplingDetailList[index].reqNo = res.data[0].reqNo;
          Object.assign(specSamplingDetailList[index], res.data[0]);
          if (res.data[0].isSign || res.data[0].isSampling) {
            specCodeInputBlur();
            let content = '当前标本';
            content += res.data[0].isSign ? `已于${res.data[0].signTime}${res.data[0].signerNa ? '被' + res.data[0].signerNa + '操作' : ''}签收\n` : '';
            content += res.data[0].isSampling ? `已于${res.data[0].samplingTime}${res.data[0].samplingDoctorNa ? '被' + res.data[0].samplingDoctorNa + '操作' : ''}采集` : '';
            content += ',需要再次采集吗？';
            const type = await VXETable.modal.confirm(content);
            if (type === 'confirm') {
              specCodeInputEnter(res.data[0].id, res.data[0].reqNo, index);
            } else if (type === 'cancel') {
              currentSpec = {};
              clearCurrentSpecsamplingDetail();
              specSamplingDetailList.splice(index, 1);
              const time = setTimeout(() => {
                clearSpecCodeInput();
                clearTimeout(time);
              }, 200);
            }

          } else {
            specCodeInputEnter(res.data[0].id, res.data[0].reqNo, index);
          }
        }

      })
      .catch((err: any) => {
        proxy.$alert(err, '提示');

      });

  } catch (err) {
    // clearSpecCodeInput();
    specCodeInputBlur();
    proxy.$alert(err.data.error.message, '提示', {
      callback: action => {
        const time = setTimeout(() => {
          clearSpecCodeInput();
          clearTimeout(time);
        }, 200);
      }
    });
  }
}


// #endRegion
//新增
function handleAdd(specCode) {
  const newRow = {
    id: null,
    reqNo: null,
    specCode,
    loading: true, //是否正在创建
    isSuccess: false //是否创建成功
  };
  specSamplingDetailList.push(newRow);
  const $table = proxy.$refs.specSamplingDetailTable as any;
  $table.reloadData(specSamplingDetailList);
  $table.setEditRow(newRow);
  $table.setCurrentRow(newRow);
  return specSamplingDetailList.length - 1;
}
// 重新采集
function againSampling(row, rowIndex) {
  if (row.id) {
    specCodeInputEnter(row.id, row.reqNo, rowIndex);
  } else {
    getspecByCode(row.reqNo);
  }
}
// 行点击事件
function specSamplingDetailRowClick({ row, rowIndex }) {
  clearCurrentSpecsamplingDetail();
  currentRowIndex = rowIndex;
  Object.assign(currentSpecsamplingDetail, row);
}

</script>
<style lang="scss" scoped>
@import '@/assets/css/isd-body.scss';

#specSampling {
  height: 100%;

  .specSamplingDetailTable {
    height: calc(100vh - 160px);
  }
}

:deep(.el-tabs__header) {
  margin: 5px 0 !important;
  border-top: solid 2px #eee;
}

:deep(.el-tabs__content) {
  padding: 0px !important;
}

:deep(.el-tab-pane) {
  height: calc(100vh - 103px);
}

:deep(.el-tabs__item) {
  padding: 0 5px !important;
}

:deep(.el-tabs__item .is-active) {
  background-color: #fff;
}
</style>
